package com.k8sops.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.k8sops.backend.mapper.DOSProjectMapper;
import com.k8sops.backend.model.entity.DOSProject;
import com.k8sops.backend.service.DOSProjectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * Project Service Implementation
 */
@Service
public class DOSProjectServiceImpl extends ServiceImpl<DOSProjectMapper, DOSProject> implements DOSProjectService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProject(DOSProject project) {
        return this.save(project);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProject(DOSProject project) {
        project.setUpdatedAt(LocalDateTime.now());
        return this.updateById(project);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProjectById(Long id) {
        // Logical delete
        DOSProject project = new DOSProject();
        project.setId(id);
        project.setDeletedAt(LocalDateTime.now());
        project.setUpdatedAt(LocalDateTime.now());
        return this.updateById(project);
    }

    @Override
    public DOSProject getProjectById(Long id) {
        return this.getById(id);
    }

    @Override
    public IPage<DOSProject> pageProjects(Integer page, Integer size, String projectName, Integer groupId) {
        Page<DOSProject> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<DOSProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(DOSProject::getDeletedAt);
        // Add filter conditions
        if (StringUtils.hasText(projectName)) {
            queryWrapper.like(DOSProject::getName, projectName);
        }
        if (groupId != null) {
            queryWrapper.eq(DOSProject::getGroupId, groupId);
        }
        
        // Sort by create time in descending order
        queryWrapper.orderByDesc(DOSProject::getCreatedAt);
        
        return this.page(pageParam, queryWrapper);
    }
}
